import requestSync from "request";
import {Mutex} from "async-mutex";
import cp from "child_process";


const mutex = new Mutex();

function performGarbageCollection() {
    if (typeof global.gc === 'function') {
        global.gc();
    } else {
        console.error('Global gc function is not exposed.');
    }
}


import {initVmSync} from "./utils.js";
import fs from "fs";
import express from "express";
import {ProxyAgent, setGlobalDispatcher} from 'undici'
import bodyParser from "body-parser";
import axios from "axios";
import {log} from "../utils/log.js";
import {addReloadCounter, resetCount} from "./monitor.js";
// 设置 HTTP 代理
// const httpDispatcher = new ProxyAgent({uri: "http://127.0.0.1:7890"});
//
// setGlobalDispatcher(httpDispatcher);

let print = console.log
let config = {
    domUrl: 'https://www.google.com/travel/flights/booking?tfs=CBwQAhpJEgoyMDI0LTExLTA2Ih8KA0hLRxIKMjAyNC0xMS0wNhoDTlJUKgJIQjIDMzIwagwIAhIIL20vMDNoNjRyDAgCEggvbS8wN2RmaxpJEgoyMDI0LTExLTIwIh8KA05SVBIKMjAyNC0xMS0yMBoDSEtHKgJIQjIDMzIzagwIAhIIL20vMDdkZmtyDAgCEggvbS8wM2g2NEABSAFwAYIBCwj___________8BmAEB&tfu=CmxDalJJZDFWaVpURnpjbFZxUkc5QlRteFpNMmRDUnkwdExTMHRMUzB0TFhSaVluZHdORUZCUVVGQlIyTlhUMDF6UVdGMk5tZEJFZ1ZJUWpNeU14b0tDSUlQRUFBYUEwaExSRGdjY0piQkFRPT0SBggAIAEoCCIA&hl=en&gl=HK',
    script_name: 'https://www.gstatic.com/',
    debug: false,
    proxy: false,
    keepRandom: false,
    body: '',
    cookie: undefined,
    cookie2: undefined,

    type: 'ksada'


}

let t1 = Date.now()
let sign = null;
let cond = false;
let signCnt = 0;
let synchronous_post = function (url, params) {

    let options = {
        url: url,
        form: params
    };

    return new Promise(function (resolve, reject) {
        requestSync.get(options, function (error, response, body) {
            if (error) {
                reject(error);
            } else {
                resolve(body);
            }
        });
    });
}

let syncBody = async function (url) {
    // let url = "http://www.baidu.com/";
    var url = url;
    let body = await synchronous_post(url);
    // console.log('##### BBBBB', body);
    return JSON.parse(body);
}

// // 在其他函数内部使用
// async function funcName(url){
//     var body = await syncBody(url);
//     console.log(body);
// }
let n = null;

function init() {
    return new Promise((resolve, reject) => {

        let inn = cp.fork("./vm/vm_run.js", {
            execArgv: ['--max-old-space-size=1024']
        });
        inn.send({
            'type': 'init',
        })
        inn.once('message', (msg) => {
            if (msg === 'initok') {
                // console.log('msg', msg)
                n = inn;


                n.on('message', (msg) => {
                    // console.log('parent got msg: ', msg);
                    // resolve(msg);
                    ResultMap.set(msg.args, msg.sign)
                    // res.send(msg)
                    // return p;
                })

                resolve(msg);
            } else if (msg === 'initerror') {
                // kill掉启动失败的进程
                try{
                    process.kill(inn.pid)
                }catch (e){

                }
                reject(new Error(msg))
            }
            // console.log('parent got msg: ', msg);
        });


    })

}

let ResultMap = new Map();


function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

export async function genBgr(args) {
    if (n === null) {
        const release = await mutex.acquire(0);
        log.warn('before', n === null);
        if (n === null) {
            try {
                log.warn('get vm')
                let r = init()
                let rr = await r
                addReloadCounter()
            } catch (e) {
                log.warn('start vm error', e)

                throw e;
            } finally {
                release();
                log.warn('release vm', n.pid)
            }
        } else {
            release();
            log.warn('release vm', n.pid)

        }
    }

    let rr = new Promise((resolve, reject) => {
        if (n.channel === null){
            log.warn('channel is null')
            reloadVM()
            reject('channel is null');
            return;
        }
        n.send({
            args: args
        });
        let cnt = 0;
        let id = setInterval(() => {
            if (ResultMap.has(args)){
                let sign = ResultMap.get(args)
                ResultMap.delete(args);
                clearInterval(id);
                resolve(sign);
            }else{
                cnt ++;
                if (cnt > 10){
                    clearInterval(id)
                    reject('timeout')
                }


            }
        }, 5)

    })
    try{
        let res = await rr
        return res;
    }catch (e){
        throw e
    }
    // let res = new Promise((e, r) => {
    //     // console.log()
    //     sign.ply(e, !0, Object.fromEntries([['mgGpzd', args]]))
    // });
    // let p = await res;
    // return p;

}

function blockMainThread(duration) {
    const startTime = Date.now();
    while (Date.now() - startTime < duration) {
        // 空循环，消耗CPU时间
    }
}

export function reloadVM() {

    let condition = false;
    resetCount()
    if (n !== null ) n.kill(0)
    if (n !== null ){
        try {
            process.kill(n.pid)
        }catch (e){
        }
    }
    n = null;

// 阻塞主线程，直到条件变为 true
    // let res = await init();

}

// fetch("http://43.135.155.176:8081/src", {
//     "headers": {
//         "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
//         "accept-language": "en,en-US;q=0.9,zh-CN;q=0.8,zh;q=0.7,ru;q=0.6",
//         "cache-control": "no-cache",
//         "pragma": "no-cache",
//         "priority": "u=0, i",
//         "sec-ch-ua": "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"",
//         "sec-ch-ua-arch": "\"x86\"",
//         "sec-ch-ua-bitness": "\"64\"",
//         "sec-ch-ua-form-factors": "\"Desktop\"",
//         "sec-ch-ua-full-version": "\"131.0.6778.86\"",
//         "sec-ch-ua-full-version-list": "\"Google Chrome\";v=\"131.0.6778.86\", \"Chromium\";v=\"131.0.6778.86\", \"Not_A Brand\";v=\"24.0.0.0\"",
//         "sec-ch-ua-mobile": "?0",
//         "sec-ch-ua-model": "\"\"",
//         "sec-ch-ua-platform": "\"macOS\"",
//         "sec-ch-ua-platform-version": "\"13.6.9\"",
//         "sec-ch-ua-wow64": "?0",
//         "sec-fetch-dest": "document",
//         "sec-fetch-mode": "navigate",
//         "sec-fetch-site": "same-origin",
//         "sec-fetch-user": "?1",
//         "upgrade-insecure-requests": "1",
//         "x-browser-channel": "stable",
//         "x-browser-copyright": "Copyright 2024 Google LLC. All rights reserved.",
//         "x-browser-validation": "f17l9rSuHmrgo31qEeG2bl8fxeI=",
//         "x-browser-year": "2024",
//         "x-client-data": "CIS2yQEIpbbJAQipncoBCO30ygEIlKHLAQic/swBCOyYzQEIhqDNAQiyns4BCP6lzgEI0MfOAQj6yc4BCIzKzgEIw8zOAQjGzM4BCKrNzgEI9c/OAQiu0M4BGJuxzgEYgMrOARiT0M4BGOrQzgE="
//     },
//     "referrerPolicy": "strict-origin-when-cross-origin",
//     "body": null,
//     "method": "GET",
//     "mode": "cors",
//     "credentials": "include"
// }).then(e => {
//     return e.json()
// }).then(e => {
//     let userCode = `
//     var _replace = String.prototype.replace;
// var _match = String.prototype.match;
// String.prototype.replace = function (oldStr, newStr) {
//     // console.log('_replace',oldStr,  this)
//     if (newStr === '\\n') {
//         console.log('_replace', oldStr, this.toString())
//         // if (this.toString().length === 7){
//         // debugger;
//         // }
//
//         // debugger;
//     }
//     let res = _replace.apply(this, arguments)
//     return res;
//
// }
// // String.prototype.match = function (mm){
// //     let res = _match.apply(this, arguments)
// //     print('_match', this.toString(), mm, '=', res);
// //     return res;
// // }
// var _concat = Array.prototype.concat;
// Array.prototype.concat = function () {
//     let res = _concat.apply(this, arguments)
//     print('_concat', this + '', arguments[0] + '')
//     return res;
//
// };
//
//     ` + e.func + `;;
//
//     let b = "${e.long_str}";;
//
//     const c = new window.ridgeslice.gc(b);
// window.sign = c;`
//
//     fs.writeFileSync('./tests/glf1.js', userCode)
//     // let userCode = fs.readFileSync('tests/dy.js', 'utf8').toString();
// // let userCode = fs.readFileSync('/Users/wang/Documents/jsvmp/learn/ksada/out2.js', 'utf8').toString();
//     let html = fs.readFileSync('demo.html', 'utf8').toString();
//     let {vm, context} = initVmSync(userCode, config, html)
//
//     //
//     // let a = "[null,\"[[null,\\\"CjRIR0hFOFRndDZLQzRBQV9nNFFCRy0tLS0tLS0tLXBmeGEyNkFBQUFBR2RRRzhjRlY4cE1BEgVXUzYwMBoLCLOfARACGgNDQUQ4HHCkcQ==\\\"],[null,null,1,null,[],1,[1,0,0,0],null,null,null,null,null,null,[[[[[\\\"YXE\\\",0]]],[[[\\\"YYC\\\",0]]],null,0,null,null,\\\"2024-12-15\\\",null,[[\\\"YXE\\\",\\\"2024-12-15\\\",\\\"YYC\\\",null,\\\"WS\\\",\\\"645\\\"]],null,null,null,null,null,3],[[[[\\\"YYC\\\",0]]],[[[\\\"YXE\\\",0]]],null,0,null,null,\\\"2024-12-29\\\",null,[[\\\"YYC\\\",\\\"2024-12-29\\\",\\\"YXE\\\",null,\\\"WS\\\",\\\"600\\\"]],null,null,null,null,null,3]],null,null,null,1],null,0]\"]";
//     // new Promise((e, r) => {
//     //     context.sign.ply(e, !0, Object.fromEntries([['mgGpzd', a]]))
//     // })
//     //     .then(e => {
//     //     fetch("https://www.google.com/_/FlightsFrontendUi/data/travel.frontend.flights.FlightsFrontendService/GetBookingResults?f.sid=-5490820794450512428&bl=boq_travel-frontend-flights-ui_20241204.02_p0&hl=en-US&gl=CA&soc-app=162&soc-platform=1&soc-device=1&_reqid=63032&rt=c", {
//     //         "headers": {
//     //             "accept": "*/*",
//     //             "accept-language": "en",
//     //             "cache-control": "no-cache",
//     //             "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
//     //             "pragma": "no-cache",
//     //             "priority": "u=1, i",
//     //             "sec-ch-ua": "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"",
//     //             "sec-ch-ua-arch": "\"arm\"",
//     //             "sec-ch-ua-bitness": "\"64\"",
//     //             "sec-ch-ua-form-factors": "\"Desktop\"",
//     //             "sec-ch-ua-full-version": "\"131.0.6778.70\"",
//     //             "sec-ch-ua-full-version-list": "\"Google Chrome\";v=\"131.0.6778.70\", \"Chromium\";v=\"131.0.6778.70\", \"Not_A Brand\";v=\"24.0.0.0\"",
//     //             "sec-ch-ua-mobile": "?0",
//     //             "sec-ch-ua-model": "\"\"",
//     //             "sec-ch-ua-platform": "\"macOS\"",
//     //             "sec-ch-ua-platform-version": "\"15.1.0\"",
//     //             "sec-ch-ua-wow64": "?0",
//     //             "sec-fetch-dest": "empty",
//     //             "sec-fetch-mode": "cors",
//     //             "sec-fetch-site": "same-origin",
//     //             "x-goog-batchexecute-bgr": "[\";"+e+"\",null,null,572,54,null,null,0,\"5\"]",
//     //             "x-goog-ext-259736195-jspb": "[\"en-US\",\"CA\",\"CAD\",1,null,[-480],null,[[97840014,97807935,97841892,72624439,97902459]],7,[]]",
//     //             "x-same-domain": "1",
//     //             "cookie": "AEC=AZ6Zc-W-bRmDzsjfS7V_i3fzkC0ppjY3fWVpLLWRW_3b-HBOX1gUTIq5EA; OTZ=7849557_24_24__24_; NID=519=Z4sBbzic4HDrxv9RYpKv74OCnvvGfPU2Ofn0-o8iPC33PpMdRJaHALpMxzzh3dm_vfusAh0ItWPkMXnQJMiEa5Q4wpsyOtf6csljcJ5SzSELg7nI8Zt1JhVKp2Hy74zJ4JwtzIM6ct4h-WUoZ_diAJOlzvmuT_sWP8K8GU_qUG6AyuTPYVu6f0VjxUnSBxpVuxO6R8_0cjjEQzT02tAfsw",
//     //             "Referer": "https://www.google.com/travel/flights/booking?tfs=CBwQAho_EgoyMDI0LTEyLTE1Ih8KA1lYRRIKMjAyNC0xMi0xNRoDWVlDKgJXUzIDNjQ1agcIARIDWVhFcgcIARIDWVlDGj8SCjIwMjQtMTItMjkiHwoDWVlDEgoyMDI0LTEyLTI5GgNZWEUqAldTMgM2MDBqBwgBEgNZWUNyBwgBEgNZWEVAAUgBcAGCAQsI____________AZgBAQ&tfu=CmxDalJJUjBoRk9GUm5kRFpMUXpSQlFWOW5ORkZDUnkwdExTMHRMUzB0TFhCbWVHRXlOa0ZCUVVGQlIyUlJSemhqUmxZNGNFMUJFZ1ZYVXpZd01Cb0xDTE9mQVJBQ0dnTkRRVVE0SEhDa2NRPT0SAggAIgMSATA&gl=CA",
//     //             "Referrer-Policy": "strict-origin-when-cross-origin"
//     //         },
//     //         "body": "f.req=%5Bnull%2C%22%5B%5Bnull%2C%5C%22CjRIR0hFOFRndDZLQzRBQV9nNFFCRy0tLS0tLS0tLXBmeGEyNkFBQUFBR2RRRzhjRlY4cE1BEgVXUzYwMBoLCLOfARACGgNDQUQ4HHCkcQ%3D%3D%5C%22%5D%2C%5Bnull%2Cnull%2C1%2Cnull%2C%5B%5D%2C1%2C%5B1%2C0%2C0%2C0%5D%2Cnull%2Cnull%2Cnull%2Cnull%2Cnull%2Cnull%2C%5B%5B%5B%5B%5B%5C%22YXE%5C%22%2C0%5D%5D%5D%2C%5B%5B%5B%5C%22YYC%5C%22%2C0%5D%5D%5D%2Cnull%2C0%2Cnull%2Cnull%2C%5C%222024-12-15%5C%22%2Cnull%2C%5B%5B%5C%22YXE%5C%22%2C%5C%222024-12-15%5C%22%2C%5C%22YYC%5C%22%2Cnull%2C%5C%22WS%5C%22%2C%5C%22645%5C%22%5D%5D%2Cnull%2Cnull%2Cnull%2Cnull%2Cnull%2C3%5D%2C%5B%5B%5B%5B%5C%22YYC%5C%22%2C0%5D%5D%5D%2C%5B%5B%5B%5C%22YXE%5C%22%2C0%5D%5D%5D%2Cnull%2C0%2Cnull%2Cnull%2C%5C%222024-12-29%5C%22%2Cnull%2C%5B%5B%5C%22YYC%5C%22%2C%5C%222024-12-29%5C%22%2C%5C%22YXE%5C%22%2Cnull%2C%5C%22WS%5C%22%2C%5C%22600%5C%22%5D%5D%2Cnull%2Cnull%2Cnull%2Cnull%2Cnull%2C3%5D%5D%2Cnull%2Cnull%2Cnull%2C1%5D%2Cnull%2C0%5D%22%5D&",
//     //         "method": "POST"
//     //     }).then(e => {
//     //         return e.text()
//     //     }).then(e => {
//     //         console.log(e.length)
//     //     })
//     // }).catch(e => {
//     //     debugger;
//     //     print(e)
//     // })
//
//
//
// })

